package com.unknowpupil.sell.service.impl;

import com.unknowpupil.sell.common.enums.ErrorCodeEnum;
import com.unknowpupil.sell.dto.OrderDTO;
import com.unknowpupil.sell.exception.SellException;
import com.unknowpupil.sell.service.BuyerService;
import com.unknowpupil.sell.service.IOrderMasterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Classname: BuyerServiceImpl
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/1/1 16:01
 * @Description:
 * @Version: 1.0
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {
    @Autowired
    private IOrderMasterService orderMasterService;
    @Override
    public OrderDTO findOrderOne(String openId, String orderId) {

        return checkOrderOwner(openId,orderId);
    }

    @Override
    public OrderDTO cancelOrder(String openId, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openId, orderId);
        if(orderDTO==null){
         log.error("[取消订单] 查找不到订单 orderId={}",orderId);
         throw new SellException(ErrorCodeEnum.ORDER_NOT_EXIST);
        }
        OrderDTO cancel = orderMasterService.cancel(orderDTO);
        return cancel;
    }

    private OrderDTO checkOrderOwner(String openId, String orderId){
        OrderDTO orderDTO = orderMasterService.finOne(orderId);
        if(orderDTO==null){
            return null;
        }
        if(!orderDTO.getBuyerOpenid().equals(openId)){
            log.error("【查询订单】订单openid 不一致。openId = {},orderDto={}",openId,orderDTO);
            throw new SellException(-1,"订单openid 不一致");
        }
        return orderDTO;
    }
}
